﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	[ToolboxData("<{0}:MyCompareValidator runat=\"server\"></{0}:MyCompareValidator>")]
	public class MyCompareValidator : System.Web.UI.WebControls.CompareValidator {
		private bool m_initialized = false;

		/// <summary>
		/// 
		/// </summary>
		protected virtual void UpdateErrorMessage() {
			if (m_initialized) {
				var fmt = "";

				switch (this.Operator) {
					case ValidationCompareOperator.Equal:
						fmt = Properties.Main.ErrorNotEqual;
						break;
					case ValidationCompareOperator.GreaterThan:
						fmt = Properties.Main.ErrorNotGreaterThan;
						break;
					case ValidationCompareOperator.GreaterThanEqual:
						fmt = Properties.Main.ErrorNotGreaterThanEqual;
						break;
					case ValidationCompareOperator.LessThan:
						fmt = Properties.Main.ErrorNotLessThan;
						break;
					case ValidationCompareOperator.LessThanEqual:
						fmt = Properties.Main.ErrorNotLessThanEqual;
						break;
					case ValidationCompareOperator.NotEqual:
						fmt = Properties.Main.ErrorEqual;
						break;
					case ValidationCompareOperator.DataTypeCheck:
						fmt = Properties.Main.ErrorNotDataType;
						break;
					default:
						throw new ArgumentException("Unkown operator \"" + this.Operator + "\".", "Operator");
				}

				ErrorMessage = string.Format(fmt, PropertyTitle, ComparisonPropertyTitle);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Category("Appearance")]
		[Bindable(true)]
		[Browsable(true)]
		[DefaultValue("")]
		public string PropertyTitle {
			get {
				var obj = ViewState["PropertyTitle"];

				return obj == null ? "" : (string)obj;
			}
			set {
				ViewState["PropertyTitle"] = value;

				UpdateErrorMessage();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Category("Appearance")]
		[Bindable(false)]
		[Browsable(true)]
		[DefaultValue("")]
		public string ComparisonPropertyTitle {
			get {
				var obj = ViewState["ComparisonPropertyTitle"];

				return obj == null ? "" : (string)obj;
			}
			set {
				ViewState["ComparisonPropertyTitle"] = value;

				UpdateErrorMessage();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
			SetFocusOnError = true;

			m_initialized = true;
			if (string.IsNullOrWhiteSpace(ErrorMessage)) {
				UpdateErrorMessage();
			}
		}
	} // end of MyFormatBaseValidator.
}
